package com.qyh.hhh;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;

import java.lang.reflect.Method;

@Slf4j
@RequiredArgsConstructor
public class TogglePointcutAdvisor extends AbstractPointcutAdvisor {
    private final ToggleMethodInterceptor toggleMethodInterceptor;

    @Override
    public Pointcut getPointcut() {
        return new StaticMethodMatcherPointcut() {
            @Override
            public boolean matches(Method method, Class<?> targetClass) {
                // 方法上面有 @Toggle注解拦截
                if (method.isAnnotationPresent(Toggle.class)) {
                    return true;
                }
                if (method.getDeclaringClass().isInterface()) {
                    String methodName = method.getName();
                    try {
                        Method targetMethod = targetClass.getMethod(methodName, method.getParameterTypes());
                        return targetMethod.isAnnotationPresent(Toggle.class);
                    } catch (NoSuchMethodException e) {
                        log.debug("FAILURE LOG HERE", e);
                        return false;
                    }
                }
                return method.isAnnotationPresent(Toggle.class);
            }
        };
    }

    @Override
    public Advice getAdvice() {
        return this.toggleMethodInterceptor;
    }
}
